const { Sequelize } = require('sequelize');
const envConfig = require('@config/env');
const logger = console; // 临时使用console替代logger，避免循环依赖

// 获取当前环境
const env = process.env.NODE_ENV || 'development';
logger.info(`当前环境变量 NODE_ENV: ${process.env.NODE_ENV}`);
logger.info(`使用环境: ${env}`);

// 获取配置
const config = envConfig[env];
logger.info('加载的配置:', envConfig);
logger.info('当前环境配置:', config);

// 检查配置是否存在
if (!config) {
  logger.error('无法获取环境配置');
  logger.error('环境变量:', process.env);
  logger.error('配置对象:', envConfig);
  process.exit(1);
}

if (!config.database) {
  logger.error('无法获取数据库配置');
  logger.error('当前配置:', config);
  process.exit(1);
}

// 输出数据库配置信息
logger.info('数据库配置:', {
  host: config.database.host,
  port: config.database.port,
  database: config.database.database,
  username: config.database.username,
  dialect: config.database.dialect
});

// 创建Sequelize实例
const sequelize = new Sequelize(
  config.database.database,
  config.database.username,
  config.database.password,
  {
    host: config.database.host,
    port: config.database.port,
    dialect: config.database.dialect,
    pool: config.database.pool,
    timezone: config.database.timezone,
    define: config.database.define,
    // 简化日志记录
    logging: config.database.logging !== false ? console.log : false
  }
);

const MAX_RETRIES = 5;
const RETRY_DELAY = 5000; // 5秒

const connectWithRetry = async (retries = MAX_RETRIES) => {
  try {
    await sequelize.authenticate();
    logger.info('数据库连接成功');
    logger.info(`连接到数据库: ${config.database.database} @ ${config.database.host}:${config.database.port}`);
  } catch (err) {
    logger.error('数据库连接失败:', err);
    logger.error('使用的配置:', {
      host: config.database.host,
      port: config.database.port,
      database: config.database.database,
      username: config.database.username
    });
    
    if (retries > 0) {
      logger.info(`将在 ${RETRY_DELAY/1000} 秒后重试连接，剩余重试次数: ${retries-1}`);
      await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
      return connectWithRetry(retries - 1);
    } else {
      logger.error('数据库连接重试次数已用完，服务启动失败');
      process.exit(1);
    }
  }
};

// 初始化数据库连接
connectWithRetry();

// 导出Sequelize实例
module.exports = sequelize; 